import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Boxes, Clock, Trophy, Star, CheckCircle, RotateCcw } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface PatternRecognitionTestProps {
  onComplete: (result: TestResult) => void;
}

interface Pattern {
  id: number;
  type: 'sequence' | 'matrix' | 'rotation' | 'color_sequence' | 'size_progression' | 'shape_pattern';
  elements: PatternElement[];
  question: PatternElement[];
  options: PatternElement[][];
  correct: number;
  difficulty: 'easy' | 'medium' | 'hard';
  description: string;
}

interface PatternElement {
  shape: 'circle' | 'square' | 'triangle' | 'diamond' | 'star' | 'hexagon';
  color: 'red' | 'blue' | 'green' | 'yellow' | 'purple' | 'orange' | 'pink' | 'black';
  size: 'small' | 'medium' | 'large';
  rotation?: number; // 0-360度
  filled?: boolean;
}

export function PatternRecognitionTest({ onComplete }: PatternRecognitionTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'results'>('instructions');
  const [currentPattern, setCurrentPattern] = useState(0);
  const [patterns, setPatterns] = useState<Pattern[]>([]);
  const [responses, setResponses] = useState<number[]>([]);
  const [timeLeft, setTimeLeft] = useState(600); // 10分钟
  const [startTime, setStartTime] = useState<number>(0);
  const [score, setScore] = useState(0);
  const [showFeedback, setShowFeedback] = useState(false);
  const [feedbackCorrect, setFeedbackCorrect] = useState(false);

  const TOTAL_PATTERNS = 15;

  // 形状渲染组件 - 修复大小和渲染问题
  const renderShape = (element: PatternElement, baseSize = 40) => {
    if (!element) {
      return <div style={{ width: baseSize, height: baseSize, backgroundColor: '#f1f5f9', border: '1px dashed #cbd5e1', borderRadius: '4px' }} />;
    }

    const { shape, color, filled = true, rotation = 0, size = 'medium' } = element;
    
    // 大幅增大尺寸差异，让大小变化非常明显
    const sizeMultiplier = size === 'small' ? 0.4 : size === 'large' ? 1.8 : 1.0;
    const actualSize = Math.round(baseSize * sizeMultiplier);
    
    const colorClass = {
      red: filled ? '#ef4444' : 'transparent',
      blue: filled ? '#3b82f6' : 'transparent',
      green: filled ? '#10b981' : 'transparent',
      yellow: filled ? '#f59e0b' : 'transparent',
      purple: filled ? '#8b5cf6' : 'transparent',
      orange: filled ? '#f97316' : 'transparent',
      pink: filled ? '#ec4899' : 'transparent',
      black: filled ? '#1f2937' : 'transparent'
    };

    const strokeColor = {
      red: '#ef4444',
      blue: '#3b82f6',
      green: '#10b981',
      yellow: '#f59e0b',
      purple: '#8b5cf6',
      orange: '#f97316',
      pink: '#ec4899',
      black: '#1f2937'
    };

    const baseProps = {
      width: actualSize,
      height: actualSize,
      viewBox: `0 0 ${actualSize} ${actualSize}`,
      fill: colorClass[color] || '#64748b',
      stroke: strokeColor[color] || '#64748b',
      strokeWidth: filled ? 0 : 2,
      style: { 
        transform: `rotate(${rotation || 0}deg)`,
        display: 'block'
      }
    };

    const padding = 2;
    const innerSize = actualSize - padding * 2;

    switch (shape) {
      case 'circle':
        return (
          <svg {...baseProps}>
            <circle 
              cx={actualSize/2} 
              cy={actualSize/2} 
              r={innerSize/2} 
            />
          </svg>
        );
      case 'square':
        return (
          <svg {...baseProps}>
            <rect 
              x={padding} 
              y={padding} 
              width={innerSize} 
              height={innerSize} 
            />
          </svg>
        );
      case 'triangle':
        return (
          <svg {...baseProps}>
            <polygon 
              points={`${actualSize/2},${padding} ${padding},${actualSize-padding} ${actualSize-padding},${actualSize-padding}`} 
            />
          </svg>
        );
      case 'diamond':
        return (
          <svg {...baseProps}>
            <polygon 
              points={`${actualSize/2},${padding} ${actualSize-padding},${actualSize/2} ${actualSize/2},${actualSize-padding} ${padding},${actualSize/2}`} 
            />
          </svg>
        );
      case 'star':
        const cx = actualSize / 2;
        const cy = actualSize / 2;
        const r1 = innerSize / 2;
        const r2 = r1 * 0.4;
        let points = '';
        for (let i = 0; i < 10; i++) {
          const r = i % 2 === 0 ? r1 : r2;
          const angle = (i * Math.PI) / 5;
          const x = cx + r * Math.cos(angle - Math.PI / 2);
          const y = cy + r * Math.sin(angle - Math.PI / 2);
          points += `${x},${y} `;
        }
        return (
          <svg {...baseProps}>
            <polygon points={points.trim()} />
          </svg>
        );
      case 'hexagon':
        const hexCx = actualSize / 2;
        const hexCy = actualSize / 2;
        const hexR = innerSize / 2;
        const hexPoints = Array.from({ length: 6 }, (_, i) => {
          const angle = (i * Math.PI) / 3;
          const x = hexCx + hexR * Math.cos(angle);
          const y = hexCy + hexR * Math.sin(angle);
          return `${x},${y}`;
        }).join(' ');
        return (
          <svg {...baseProps}>
            <polygon points={hexPoints} />
          </svg>
        );
      default:
        return (
          <div 
            style={{ 
              width: actualSize, 
              height: actualSize, 
              backgroundColor: '#f1f5f9', 
              border: '1px solid #e2e8f0',
              borderRadius: '4px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              fontSize: '10px',
              color: '#64748b'
            }}
          >
            ?
          </div>
        );
    }
  };

  // 生成模式题目 - 增强随机性和多样性
  const generatePatterns = (): Pattern[] => {
    const patterns: Pattern[] = [];
    let patternId = 1;

    // 随机分配题目数量，确保总数为15道
    const baseDistribution = [4, 3, 3, 2, 2, 1]; // 序列、矩阵、旋转、颜色、大小、形状
    const totalAdjustment = Math.floor(Math.random() * 3) - 1; // -1, 0, 或 1
    
    // 随机调整分布
    let distribution = [...baseDistribution];
    if (totalAdjustment !== 0) {
      const randomIndex1 = Math.floor(Math.random() * distribution.length);
      let randomIndex2 = Math.floor(Math.random() * distribution.length);
      while (randomIndex2 === randomIndex1) {
        randomIndex2 = Math.floor(Math.random() * distribution.length);
      }
      
      if (distribution[randomIndex1] > 1) {
        distribution[randomIndex1] += totalAdjustment;
        distribution[randomIndex2] -= totalAdjustment;
      }
    }

    // 序列模式 (3-5道)
    for (let i = 0; i < distribution[0]; i++) {
      patterns.push(generateSequencePattern(patternId++));
    }

    // 矩阵模式 (2-4道)
    for (let i = 0; i < distribution[1]; i++) {
      patterns.push(generateMatrixPattern(patternId++));
    }

    // 旋转模式 (2-4道)
    for (let i = 0; i < distribution[2]; i++) {
      patterns.push(generateRotationPattern(patternId++));
    }

    // 颜色序列 (1-3道)
    for (let i = 0; i < distribution[3]; i++) {
      patterns.push(generateColorSequencePattern(patternId++));
    }

    // 大小渐变 (1-3道)
    for (let i = 0; i < distribution[4]; i++) {
      patterns.push(generateSizeProgressionPattern(patternId++));
    }

    // 形状模式 (1-2道)
    for (let i = 0; i < distribution[5]; i++) {
      patterns.push(generateShapePattern(patternId++));
    }

    // 添加一些复合模式（形状+颜色组合）
    if (patterns.length < TOTAL_PATTERNS) {
      const remaining = TOTAL_PATTERNS - patterns.length;
      for (let i = 0; i < remaining; i++) {
        patterns.push(generateComplexPattern(patternId++));
      }
    }

    // 更强的随机化
    for (let i = patterns.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [patterns[i], patterns[j]] = [patterns[j], patterns[i]];
    }

    return patterns.slice(0, TOTAL_PATTERNS);
  };

  const generateSequencePattern = (id: number): Pattern => {
    const shapes = ['circle', 'square', 'triangle', 'diamond', 'star', 'hexagon'] as const;
    const colors = ['red', 'blue', 'green', 'yellow', 'purple', 'orange', 'pink'] as const;
    
    const patternTypes = ['shape_cycle', 'color_cycle', 'alternating', 'growing_cycle', 'mixed_attribute'];
    const patternType = patternTypes[Math.floor(Math.random() * patternTypes.length)];
    
    if (patternType === 'shape_cycle') {
      // 随机循环长度：3-5
      const cycleLength = Math.floor(Math.random() * 3) + 3; // 3, 4, 5
      const selectedShapes = shapes.slice(0, cycleLength);
      const elements = [];
      const color = colors[Math.floor(Math.random() * colors.length)];
      
      for (let i = 0; i < 5; i++) {
        elements.push({
          shape: selectedShapes[i % cycleLength],
          color,
          size: 'medium' as const,
          filled: true
        });
      }

      const nextShape = selectedShapes[5 % cycleLength];
      
      const options = [
        [{ shape: nextShape, color, size: 'medium' as const, filled: true }], // 正确答案
        [{ shape: selectedShapes[(5 + 1) % cycleLength], color, size: 'medium' as const, filled: true }],
        [{ shape: selectedShapes[(5 + 2) % cycleLength], color, size: 'medium' as const, filled: true }],
        [{ shape: shapes[shapes.length - 1], color, size: 'medium' as const, filled: true }]
      ];

      return {
        id,
        type: 'sequence',
        elements,
        question: [{ shape: nextShape, color, size: 'medium' as const, filled: true }],
        options,
        correct: 0,
        difficulty: 'easy',
        description: `找出${cycleLength}元素形状循环规律的下一个元素`
      };
    } else if (patternType === 'color_cycle') {
      const shape = shapes[Math.floor(Math.random() * shapes.length)];
      const cycleLength = Math.floor(Math.random() * 3) + 3; // 3, 4, 5
      const selectedColors = colors.slice(0, cycleLength);
      const elements = [];
      
      for (let i = 0; i < 5; i++) {
        elements.push({
          shape,
          color: selectedColors[i % cycleLength],
          size: 'medium' as const,
          filled: true
        });
      }

      const nextColor = selectedColors[5 % cycleLength];
      
      const options = [
        [{ shape, color: nextColor, size: 'medium' as const, filled: true }], // 正确答案
        [{ shape, color: selectedColors[(5 + 1) % cycleLength], size: 'medium' as const, filled: true }],
        [{ shape, color: selectedColors[(5 + 2) % cycleLength], size: 'medium' as const, filled: true }],
        [{ shape, color: colors[colors.length - 1], size: 'medium' as const, filled: true }]
      ];

      return {
        id,
        type: 'sequence',
        elements,
        question: [{ shape, color: nextColor, size: 'medium' as const, filled: true }],
        options,
        correct: 0,
        difficulty: 'medium',
        description: `找出${cycleLength}元素颜色循环规律的下一个元素`
      };
    } else if (patternType === 'growing_cycle') {
      // 成长循环：大小和形状都变化
      const baseShape = shapes[Math.floor(Math.random() * 3)]; // 使用前3种基础形状
      const color = colors[Math.floor(Math.random() * colors.length)];
      const sizes = ['small', 'medium', 'large'] as const;
      
      const elements = [
        { shape: baseShape, color, size: 'small' as const, filled: true },
        { shape: shapes[1], color, size: 'medium' as const, filled: true },
        { shape: shapes[2], color, size: 'large' as const, filled: true },
        { shape: baseShape, color, size: 'small' as const, filled: true },
        { shape: shapes[1], color, size: 'medium' as const, filled: true }
      ];

      const nextElement = { shape: shapes[2], color, size: 'large' as const, filled: true };
      
      const options = [
        [nextElement], // 正确答案
        [{ shape: baseShape, color, size: 'large' as const, filled: true }],
        [{ shape: shapes[2], color, size: 'small' as const, filled: true }],
        [{ shape: shapes[3], color, size: 'medium' as const, filled: true }]
      ];

      return {
        id,
        type: 'sequence',
        elements,
        question: [nextElement],
        options,
        correct: 0,
        difficulty: 'hard',
        description: '找出形状和大小组合循环的下一个元素'
      };
    } else if (patternType === 'mixed_attribute') {
      // 混合属性：形状、颜色、填充状态
      const shape1 = shapes[Math.floor(Math.random() * shapes.length)];
      const shape2 = shapes[Math.floor(Math.random() * shapes.length)];
      const color1 = colors[Math.floor(Math.random() * colors.length)];
      const color2 = colors[Math.floor(Math.random() * colors.length)];
      
      const elements = [
        { shape: shape1, color: color1, size: 'medium' as const, filled: true },
        { shape: shape2, color: color2, size: 'medium' as const, filled: false },
        { shape: shape1, color: color1, size: 'medium' as const, filled: true },
        { shape: shape2, color: color2, size: 'medium' as const, filled: false },
        { shape: shape1, color: color1, size: 'medium' as const, filled: true }
      ];

      const nextElement = { shape: shape2, color: color2, size: 'medium' as const, filled: false };
      
      const options = [
        [nextElement], // 正确答案
        [{ shape: shape2, color: color2, size: 'medium' as const, filled: true }],
        [{ shape: shape1, color: color2, size: 'medium' as const, filled: false }],
        [{ shape: shape2, color: color1, size: 'medium' as const, filled: false }]
      ];

      return {
        id,
        type: 'sequence',
        elements,
        question: [nextElement],
        options,
        correct: 0,
        difficulty: 'hard',
        description: '找出多重属性交替模式的下一个元素'
      };
    } else {
      // 简单交替
      const shape1 = shapes[Math.floor(Math.random() * shapes.length)];
      let shape2 = shapes[Math.floor(Math.random() * shapes.length)];
      while (shape2 === shape1) {
        shape2 = shapes[Math.floor(Math.random() * shapes.length)];
      }
      
      const color1 = colors[Math.floor(Math.random() * colors.length)];
      let color2 = colors[Math.floor(Math.random() * colors.length)];
      while (color2 === color1) {
        color2 = colors[Math.floor(Math.random() * colors.length)];
      }
      
      const elements = [
        { shape: shape1, color: color1, size: 'medium' as const, filled: true },
        { shape: shape2, color: color2, size: 'medium' as const, filled: true },
        { shape: shape1, color: color1, size: 'medium' as const, filled: true },
        { shape: shape2, color: color2, size: 'medium' as const, filled: true },
        { shape: shape1, color: color1, size: 'medium' as const, filled: true }
      ];

      const nextElement = { shape: shape2, color: color2, size: 'medium' as const, filled: true };
      
      const options = [
        [nextElement], // 正确答案
        [{ shape: shape1, color: color1, size: 'medium' as const, filled: true }],
        [{ shape: shape1, color: color2, size: 'medium' as const, filled: true }],
        [{ shape: shape2, color: color1, size: 'medium' as const, filled: true }]
      ];

      return {
        id,
        type: 'sequence',
        elements,
        question: [nextElement],
        options,
        correct: 0,
        difficulty: 'easy',
        description: '找出交替模式的下一个元素'
      };
    }
  };

  const generateMatrixPattern = (id: number): Pattern => {
    const shapes = ['circle', 'square', 'triangle', 'diamond'] as const;
    const colors = ['red', 'blue', 'green', 'yellow', 'purple'] as const;
    
    const matrixTypes = ['color_addition', 'shape_rotation', 'size_pattern', 'fill_pattern'];
    const matrixType = matrixTypes[Math.floor(Math.random() * matrixTypes.length)];
    
    const elements = [];
    let correctElement: PatternElement;
    let description: string;

    if (matrixType === 'color_addition') {
      // 颜色加法矩阵：每行和每列的颜色有规律
      const selectedColors = colors.slice(0, 3);
      const baseShape = shapes[Math.floor(Math.random() * shapes.length)];
      
      for (let row = 0; row < 3; row++) {
        for (let col = 0; col < 3; col++) {
          if (row === 2 && col === 2) continue; // 跳过右下角
          
          elements.push({
            shape: baseShape,
            color: selectedColors[(row + col) % selectedColors.length],
            size: 'medium' as const,
            filled: true
          });
        }
      }

      const correctColor = selectedColors[(2 + 2) % selectedColors.length];
      correctElement = { shape: baseShape, color: correctColor, size: 'medium' as const, filled: true };
      description = '找出颜色规律矩阵中缺失的元素';
    } else if (matrixType === 'shape_rotation') {
      // 形状变化矩阵：每行形状不同，每列保持一致
      const selectedShapes = shapes.slice(0, 3);
      const color = colors[Math.floor(Math.random() * colors.length)];
      
      for (let row = 0; row < 3; row++) {
        for (let col = 0; col < 3; col++) {
          if (row === 2 && col === 2) continue; // 跳过右下角
          
          elements.push({
            shape: selectedShapes[col],
            color,
            size: 'medium' as const,
            filled: true
          });
        }
      }

      correctElement = { shape: selectedShapes[2], color, size: 'medium' as const, filled: true };
      description = '找出形状模式矩阵中缺失的元素';
    } else if (matrixType === 'size_pattern') {
      // 大小模式矩阵：每行大小递增
      const baseShape = shapes[Math.floor(Math.random() * shapes.length)];
      const color = colors[Math.floor(Math.random() * colors.length)];
      const sizes = ['small', 'medium', 'large'] as const;
      
      for (let row = 0; row < 3; row++) {
        for (let col = 0; col < 3; col++) {
          if (row === 2 && col === 2) continue; // 跳过右下角
          
          elements.push({
            shape: baseShape,
            color,
            size: sizes[col],
            filled: true
          });
        }
      }

      correctElement = { shape: baseShape, color, size: 'large', filled: true };
      description = '找出大小模式矩阵中缺失的元素';
    } else {
      // 填充模式矩阵：填充状态有规律
      const baseShape = shapes[Math.floor(Math.random() * shapes.length)];
      const color = colors[Math.floor(Math.random() * colors.length)];
      
      for (let row = 0; row < 3; row++) {
        for (let col = 0; col < 3; col++) {
          if (row === 2 && col === 2) continue; // 跳过右下角
          
          elements.push({
            shape: baseShape,
            color,
            size: 'medium' as const,
            filled: (row + col) % 2 === 0
          });
        }
      }

      correctElement = { shape: baseShape, color, size: 'medium' as const, filled: (2 + 2) % 2 === 0 };
      description = '找出填充模式矩阵中缺失的元素';
    }
    
    // 生成更多样化的错误选项
    const otherShapes = shapes.filter(s => s !== correctElement.shape);
    const otherColors = colors.filter(c => c !== correctElement.color);
    
    const options = [
      [correctElement], // 正确答案
      [{ ...correctElement, color: otherColors[0] }],
      [{ ...correctElement, shape: otherShapes[0] }],
      [{ ...correctElement, filled: !correctElement.filled }]
    ];

    return {
      id,
      type: 'matrix',
      elements,
      question: [correctElement],
      options,
      correct: 0,
      difficulty: 'medium',
      description
    };
  };

  const generateRotationPattern = (id: number): Pattern => {
    const shapes = ['triangle', 'diamond', 'star', 'hexagon'] as const;
    const colors = ['blue', 'purple', 'green', 'red', 'orange'] as const;
    const shape = shapes[Math.floor(Math.random() * shapes.length)];
    const color = colors[Math.floor(Math.random() * colors.length)];
    
    const rotationTypes = ['clockwise_90', 'clockwise_45', 'counterclockwise_90', 'clockwise_60', 'alternating'];
    const rotationType = rotationTypes[Math.floor(Math.random() * rotationTypes.length)];
    
    let elements: PatternElement[] = [];
    let correctElement: PatternElement;
    let description: string;

    if (rotationType === 'clockwise_90') {
      // 顺时针90度递增：0° -> 90° -> 180° -> 270° -> 0°
      for (let i = 0; i < 4; i++) {
        elements.push({
          shape, color, size: 'medium' as const,
          rotation: i * 90, filled: true
        });
      }
      correctElement = { shape, color, size: 'medium' as const, rotation: 0, filled: true };
      description = '找出顺时针90度旋转规律的下一个元素';
    } else if (rotationType === 'clockwise_45') {
      // 顺时针45度递增：0° -> 45° -> 90° -> 135° -> 180°
      for (let i = 0; i < 4; i++) {
        elements.push({
          shape, color, size: 'medium' as const,
          rotation: i * 45, filled: true
        });
      }
      correctElement = { shape, color, size: 'medium' as const, rotation: 180, filled: true };
      description = '找出顺时针45度旋转规律的下一个元素';
    } else if (rotationType === 'counterclockwise_90') {
      // 逆时针90度递增：0° -> 270° -> 180° -> 90° -> 0°
      const rotations = [0, 270, 180, 90];
      for (let i = 0; i < 4; i++) {
        elements.push({
          shape, color, size: 'medium' as const,
          rotation: rotations[i], filled: true
        });
      }
      correctElement = { shape, color, size: 'medium' as const, rotation: 0, filled: true };
      description = '找出逆时针90度旋转规律的下一个元素';
    } else if (rotationType === 'clockwise_60') {
      // 顺时针60度递增：0° -> 60° -> 120° -> 180° -> 240°
      for (let i = 0; i < 4; i++) {
        elements.push({
          shape, color, size: 'medium' as const,
          rotation: i * 60, filled: true
        });
      }
      correctElement = { shape, color, size: 'medium' as const, rotation: 240, filled: true };
      description = '找出顺时针60度旋转规律的下一个元素';
    } else {
      // 交替旋转：0° -> 90° -> 0° -> 90° -> 0°
      const rotations = [0, 90, 0, 90];
      for (let i = 0; i < 4; i++) {
        elements.push({
          shape, color, size: 'medium' as const,
          rotation: rotations[i], filled: true
        });
      }
      correctElement = { shape, color, size: 'medium' as const, rotation: 0, filled: true };
      description = '找出交替旋转规律的下一个元素';
    }
    
    // 生成不同的错误选项，确保有明显区别
    const correctRotation = correctElement.rotation;
    const wrongRotations = [
      (correctRotation + 45) % 360,
      (correctRotation + 90) % 360,
      (correctRotation + 180) % 360
    ];
    
    const options = [
      [correctElement], // 正确答案
      [{ shape, color, size: 'medium' as const, rotation: wrongRotations[0], filled: true }],
      [{ shape, color, size: 'medium' as const, rotation: wrongRotations[1], filled: true }],
      [{ shape, color, size: 'medium' as const, rotation: wrongRotations[2], filled: true }]
    ];

    return {
      id,
      type: 'rotation',
      elements,
      question: [correctElement],
      options,
      correct: 0,
      difficulty: 'hard',
      description
    };
  };

  const generateColorSequencePattern = (id: number): Pattern => {
    const shapes = ['circle', 'square', 'triangle', 'diamond'] as const;
    const shape = shapes[Math.floor(Math.random() * shapes.length)];
    
    const colorSequenceTypes = ['rainbow', 'warm_cool', 'primary_secondary', 'monochrome'];
    const sequenceType = colorSequenceTypes[Math.floor(Math.random() * colorSequenceTypes.length)];
    
    let colors: string[];
    let elements: PatternElement[];
    let correctElement: PatternElement;
    let description: string;

    if (sequenceType === 'rainbow') {
      // 彩虹序列
      colors = ['red', 'yellow', 'green', 'blue'];
      elements = colors.slice(0, 3).map(color => ({
        shape, color, size: 'medium' as const, filled: true
      }));
      correctElement = { shape, color: colors[3], size: 'medium' as const, filled: true };
      description = '找出彩虹色序列的下一个元素';
    } else if (sequenceType === 'warm_cool') {
      // 暖冷色交替
      colors = ['red', 'blue', 'orange', 'green'];
      elements = colors.slice(0, 3).map(color => ({
        shape, color, size: 'medium' as const, filled: true
      }));
      correctElement = { shape, color: colors[3], size: 'medium' as const, filled: true };
      description = '找出暖冷色交替序列的下一个元素';
    } else if (sequenceType === 'primary_secondary') {
      // 原色到间色
      colors = ['red', 'purple', 'blue', 'green'];
      elements = colors.slice(0, 3).map(color => ({
        shape, color, size: 'medium' as const, filled: true
      }));
      correctElement = { shape, color: colors[3], size: 'medium' as const, filled: true };
      description = '找出色彩演变序列的下一个元素';
    } else {
      // 单色系深浅变化（用填充状态模拟）
      const baseColor = ['blue', 'red', 'green'][Math.floor(Math.random() * 3)];
      elements = [
        { shape, color: baseColor, size: 'small' as const, filled: true },
        { shape, color: baseColor, size: 'medium' as const, filled: true },
        { shape, color: baseColor, size: 'large' as const, filled: false }
      ];
      correctElement = { shape, color: baseColor, size: 'large' as const, filled: true };
      description = '找出单色系变化序列的下一个元素';
    }
    
    // 生成多样化的错误选项
    const allColors = ['red', 'blue', 'green', 'yellow', 'purple', 'orange', 'pink'];
    const wrongColors = allColors.filter(c => c !== correctElement.color).slice(0, 3);
    
    const options = [
      [correctElement], // 正确答案
      [{ ...correctElement, color: wrongColors[0] }],
      [{ ...correctElement, color: wrongColors[1] }],
      [{ ...correctElement, color: wrongColors[2] }]
    ];

    return {
      id,
      type: 'color_sequence',
      elements,
      question: [correctElement],
      options,
      correct: 0,
      difficulty: 'easy',
      description
    };
  };

  const generateSizeProgressionPattern = (id: number): Pattern => {
    const shapes = ['square', 'circle', 'triangle', 'diamond'] as const;
    const colors = ['purple', 'blue', 'green', 'orange', 'red'] as const;
    const shape = shapes[Math.floor(Math.random() * shapes.length)];
    const color = colors[Math.floor(Math.random() * colors.length)];
    
    const progressionTypes = ['increasing', 'decreasing', 'wave', 'cycle_forward'];
    const progressionType = progressionTypes[Math.floor(Math.random() * progressionTypes.length)];
    
    let elements: PatternElement[] = [];
    let correctElement: PatternElement;
    let description: string;

    if (progressionType === 'increasing') {
      // 递增：small -> medium -> large -> 超大 (用large表示，但在显示时会更大)
      elements = [
        { shape, color, size: 'small', filled: true },
        { shape, color, size: 'medium', filled: true },
        { shape, color, size: 'large', filled: true }
      ];
      // 继续递增，使用large但标记为"超大"
      correctElement = { shape, color, size: 'large', filled: true };
      description = '找出递增大小规律的下一个元素（从小到大）';
    } else if (progressionType === 'decreasing') {
      // 递减：large -> medium -> small -> 超小
      elements = [
        { shape, color, size: 'large', filled: true },
        { shape, color, size: 'medium', filled: true },
        { shape, color, size: 'small', filled: true }
      ];
      // 继续递减
      correctElement = { shape, color, size: 'small', filled: true };
      description = '找出递减大小规律的下一个元素（从大到小）';
    } else if (progressionType === 'wave') {
      // 波浪：small -> large -> small -> large -> small
      elements = [
        { shape, color, size: 'small', filled: true },
        { shape, color, size: 'large', filled: true },
        { shape, color, size: 'small', filled: true },
        { shape, color, size: 'large', filled: true }
      ];
      correctElement = { shape, color, size: 'small', filled: true };
      description = '找出大小交替规律的下一个元素（大小波动）';
    } else {
      // 正向循环：small -> medium -> large -> small -> medium
      elements = [
        { shape, color, size: 'small', filled: true },
        { shape, color, size: 'medium', filled: true },
        { shape, color, size: 'large', filled: true },
        { shape, color, size: 'small', filled: true }
      ];
      correctElement = { shape, color, size: 'medium', filled: true };
      description = '找出大小循环规律的下一个元素（小→中→大→小）';
    }
    
    // 确保选项中有明显的大小差异
    const allSizes = ['small', 'medium', 'large'] as const;
    const wrongSizes = allSizes.filter(s => s !== correctElement.size);
    
    const options = [
      [correctElement], // 正确答案
      [{ shape, color, size: wrongSizes[0], filled: true }],
      [{ shape, color, size: wrongSizes[1], filled: true }],
      [{ shape: shapes[(shapes.indexOf(shape) + 1) % shapes.length], color, size: correctElement.size, filled: true }] // 形状错误但大小正确
    ];

    return {
      id,
      type: 'size_progression',
      elements,
      question: [correctElement],
      options,
      correct: 0,
      difficulty: 'medium',
      description
    };
  };

  const generateShapePattern = (id: number): Pattern => {
    const colors = ['green', 'blue', 'purple', 'red', 'orange'] as const;
    const color = colors[Math.floor(Math.random() * colors.length)];
    
    const patternTypes = ['edge_increasing', 'complexity_increasing', 'symmetry_pattern'];
    const patternType = patternTypes[Math.floor(Math.random() * patternTypes.length)];
    
    if (patternType === 'edge_increasing') {
      // 边数递增：圆(∞) -> 三角形(3) -> 正方形(4) -> 六边形(6)
      const shapes = ['circle', 'triangle', 'square', 'hexagon'] as const;
      const elements = shapes.slice(0, 3).map(shape => ({
        shape, color, size: 'medium' as const, filled: true
      }));

      const correctElement = { shape: shapes[3], color, size: 'medium' as const, filled: true };
      
      const options = [
        [correctElement], // 正确答案：六边形
        [{ shape: 'star', color, size: 'medium' as const, filled: true }], // 星形
        [{ shape: 'diamond', color, size: 'medium' as const, filled: true }], // 菱形
        [{ shape: shapes[0], color, size: 'medium' as const, filled: true }] // 圆形
      ];

      return {
        id,
        type: 'shape_pattern',
        elements,
        question: [correctElement],
        options,
        correct: 0,
        difficulty: 'hard',
        description: '找出边数递增规律的下一个元素'
      };
    } else if (patternType === 'complexity_increasing') {
      // 复杂度递增：圆 -> 正方形 -> 菱形 -> 星形
      const shapes = ['circle', 'square', 'diamond', 'star'] as const;
      const elements = shapes.slice(0, 3).map(shape => ({
        shape, color, size: 'medium' as const, filled: true
      }));

      const correctElement = { shape: shapes[3], color, size: 'medium' as const, filled: true };
      
      const options = [
        [correctElement], // 正确答案：星形
        [{ shape: 'hexagon', color, size: 'medium' as const, filled: true }], // 六边形
        [{ shape: 'triangle', color, size: 'medium' as const, filled: true }], // 三角形
        [{ shape: shapes[0], color, size: 'medium' as const, filled: true }] // 圆形
      ];

      return {
        id,
        type: 'shape_pattern',
        elements,
        question: [correctElement],
        options,
        correct: 0,
        difficulty: 'hard',
        description: '找出复杂度递增规律的下一个元素'
      };
    } else {
      // 对称性模式：圆(完全对称) -> 正方形(4重对称) -> 三角形(3重对称) -> 菱形(2重对称)
      const shapes = ['circle', 'square', 'triangle', 'diamond'] as const;
      const elements = shapes.slice(0, 3).map(shape => ({
        shape, color, size: 'medium' as const, filled: true
      }));

      const correctElement = { shape: shapes[3], color, size: 'medium' as const, filled: true };
      
      const options = [
        [correctElement], // 正确答案：菱形
        [{ shape: 'star', color, size: 'medium' as const, filled: true }], // 星形
        [{ shape: 'hexagon', color, size: 'medium' as const, filled: true }], // 六边形
        [{ shape: shapes[1], color, size: 'medium' as const, filled: true }] // 正方形
      ];

      return {
        id,
        type: 'shape_pattern',
        elements,
        question: [correctElement],
        options,
        correct: 0,
        difficulty: 'hard',
        description: '找出对称性递减规律的下一个元素'
      };
    }
  };

  // 新增：复合模式生成器
  const generateComplexPattern = (id: number): Pattern => {
    const shapes = ['circle', 'square', 'triangle', 'diamond'] as const;
    const colors = ['red', 'blue', 'green', 'yellow'] as const;
    const sizes = ['small', 'medium', 'large'] as const;
    
    // 双重规律：形状和颜色同时变化
    const elements = [
      { shape: shapes[0], color: colors[0], size: sizes[0], filled: true },
      { shape: shapes[1], color: colors[1], size: sizes[1], filled: true },
      { shape: shapes[2], color: colors[2], size: sizes[2], filled: true }
    ];

    const correctElement = { shape: shapes[3], color: colors[3] || colors[0], size: sizes[0], filled: true };
    
    const options = [
      [correctElement], // 正确答案
      [{ shape: shapes[3], color: colors[0], size: sizes[2], filled: true }],
      [{ shape: shapes[0], color: colors[3] || colors[0], size: sizes[0], filled: true }],
      [{ shape: shapes[2], color: colors[2], size: sizes[1], filled: true }]
    ];

    return {
      id,
      type: 'sequence',
      elements,
      question: [correctElement],
      options,
      correct: 0,
      difficulty: 'hard',
      description: '找出多重属性组合规律的下一个元素'
    };
  };

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            setStage('results');
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft]);

  const handleStartTest = () => {
    const generatedPatterns = generatePatterns();
    setPatterns(generatedPatterns);
    setStage('test');
    setStartTime(Date.now());
  };

  const handleAnswer = (answerIndex: number) => {
    const pattern = patterns[currentPattern];
    const correct = answerIndex === pattern.correct;
    
    setResponses(prev => [...prev, answerIndex]);
    
    if (correct) {
      setScore(prev => prev + 1);
    }
    
    // 显示反馈
    setFeedbackCorrect(correct);
    setShowFeedback(true);
    
    setTimeout(() => {
      setShowFeedback(false);
      
      if (currentPattern < patterns.length - 1) {
        setCurrentPattern(prev => prev + 1);
      } else {
        setStage('results');
      }
    }, correct ? 1500 : 2500); // 错误答案显示更长时间
  };

  const handleComplete = () => {
    const totalPatterns = patterns.length;
    const correctAnswers = score;
    const accuracy = Math.round((correctAnswers / totalPatterns) * 100);
    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    // 按模式类型统计
    const typeStats: { [key: string]: { correct: number; total: number } } = {};
    
    patterns.forEach((pattern, index) => {
      const type = pattern.type;
      if (!typeStats[type]) {
        typeStats[type] = { correct: 0, total: 0 };
      }
      typeStats[type].total++;
      if (responses[index] === pattern.correct) {
        typeStats[type].correct++;
      }
    });

    const result: TestResult = {
      id: Date.now().toString(),
      testType: '模式识别测试',
      score: accuracy,
      details: `准确率 ${accuracy}%, 完成 ${totalPatterns} 题, 平均每题 ${Math.round(timeUsed / totalPatterns)} 秒`,
      timestamp: new Date()
    };

    onComplete(result);
  };

  const resetTest = () => {
    setStage('instructions');
    setCurrentPattern(0);
    setPatterns([]);
    setResponses([]);
    setScore(0);
    setShowFeedback(false);
    setTimeLeft(600);
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-orange-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-orange-600 to-red-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Boxes className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">模式识别测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您识别和理解视觉模式的能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-orange-50 to-red-50 rounded-xl p-6 border border-orange-100">
              <h3 className="font-semibold text-orange-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>观察给定的图形序列或矩阵模式</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>找出其中的规律（形状、颜色、大小、旋转等）</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>从选项中选择符合规律的下一个元素</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-orange-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>答错时会显示正确答案和解释</p>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-2 gap-4">
              <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-4 border border-blue-200">
                <h4 className="font-semibold text-blue-800 mb-2">序列模式</h4>
                <p className="text-sm text-blue-700">线性排列的图形规律</p>
              </div>
              <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-xl p-4 border border-green-200">
                <h4 className="font-semibold text-green-800 mb-2">矩阵模式</h4>
                <p className="text-sm text-green-700">二维网格中的图形关系</p>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl border border-orange-200">
                <div className="text-2xl font-bold text-orange-600 mb-1">6</div>
                <div className="text-sm text-orange-700">模式类型</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-red-50 to-red-100 rounded-xl border border-red-200">
                <div className="text-2xl font-bold text-red-600 mb-1">15</div>
                <div className="text-sm text-red-700">动态题目</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-orange-50 to-red-50 rounded-xl border border-orange-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">10</div>
                <div className="text-sm text-slate-700">分钟限时</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test' && patterns.length > 0) {
    const pattern = patterns[currentPattern];
    const progress = ((currentPattern + 1) / patterns.length) * 100;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-orange-100 text-orange-700 border-orange-300">
              模式 {currentPattern + 1} / {patterns.length}
            </Badge>
            <Badge variant="outline" className={`${
              pattern.type === 'sequence' ? 'bg-blue-100 text-blue-700 border-blue-300' :
              pattern.type === 'matrix' ? 'bg-green-100 text-green-700 border-green-300' :
              pattern.type === 'rotation' ? 'bg-purple-100 text-purple-700 border-purple-300' :
              pattern.type === 'color_sequence' ? 'bg-yellow-100 text-yellow-700 border-yellow-300' :
              pattern.type === 'size_progression' ? 'bg-pink-100 text-pink-700 border-pink-300' :
              'bg-indigo-100 text-indigo-700 border-indigo-300'
            }`}>
              {pattern.type === 'sequence' ? '序列模式' :
               pattern.type === 'matrix' ? '矩阵模式' :
               pattern.type === 'rotation' ? '旋转模式' :
               pattern.type === 'color_sequence' ? '颜色序列' :
               pattern.type === 'size_progression' ? '大小渐变' : '形状模式'}
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{score}</span>
            </div>
          </div>
          
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-slate-500" />
            <span className={`font-mono text-lg font-bold ${timeLeft <= 60 ? 'text-red-500' : 'text-slate-700'}`}>
              {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')}
            </span>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 模式显示区域 */}
        <Card className="bg-white/90 backdrop-blur-sm border-orange-200 shadow-lg">
          <CardHeader>
            <CardTitle className="text-lg text-slate-800">{pattern.description}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* 模式元素显示 */}
            <div className="bg-slate-50 rounded-lg p-6">
              <h4 className="text-md font-semibold text-slate-700 mb-4">观察规律：</h4>
              <div className={`flex items-center justify-center gap-4 ${
                pattern.type === 'matrix' ? 'grid grid-cols-3 gap-6 max-w-sm mx-auto' : 
                pattern.type === 'size_progression' ? 'flex items-end gap-8' : 'flex-wrap'
              }`}>
                {pattern.elements.map((element, index) => (
                  <motion.div
                    key={index}
                    initial={{ opacity: 0, scale: 0.8 }}
                    animate={{ opacity: 1, scale: 1 }}
                    transition={{ delay: index * 0.1 }}
                    className={`flex items-center justify-center p-3 ${
                      pattern.type === 'size_progression' ? 'min-h-[120px] min-w-[120px]' : 'min-h-[60px] min-w-[60px]'
                    }`}
                  >
                    {renderShape(element, pattern.type === 'size_progression' ? 80 : 50)}
                  </motion.div>
                ))}
                {pattern.type === 'matrix' && (
                  <div className="flex items-center justify-center p-2 border-2 border-dashed border-slate-300 rounded bg-white min-h-[60px] min-w-[60px]">
                    <span className="text-2xl text-slate-400">?</span>
                  </div>
                )}
                {pattern.type !== 'matrix' && (
                  <div className={`flex items-center justify-center p-3 ${
                    pattern.type === 'size_progression' ? 'min-h-[120px] min-w-[120px]' : 'min-h-[60px] min-w-[60px]'
                  }`}>
                    <span className="text-2xl text-slate-400">→ ?</span>
                  </div>
                )}
              </div>
              {pattern.type === 'size_progression' && (
                <div className="mt-6 text-center">
                  <p className="text-sm text-slate-600 font-medium">
                    🔍 仔细观察图形的大小变化规律
                  </p>
                  <p className="text-xs text-slate-500 mt-1">
                    图形会逐渐变大或变小，请选择符合规律的下一个图形
                  </p>
                </div>
              )}
            </div>

            {/* 选项 */}
            <div>
              <h4 className="text-md font-semibold text-slate-700 mb-4">选择正确答案：</h4>
              <div className={`grid ${pattern.type === 'size_progression' ? 'grid-cols-2 sm:grid-cols-4 gap-6' : 'grid-cols-2 sm:grid-cols-4 gap-4'}`}>
                {pattern.options.map((option, index) => (
                  <motion.div
                    key={index}
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                  >
                    <Button
                      variant="outline"
                      onClick={() => handleAnswer(index)}
                      disabled={showFeedback}
                      className={`w-full transition-all duration-300 flex items-center justify-center ${
                        pattern.type === 'size_progression' ? 'h-40 p-6' : 'h-28 p-4'
                      } ${
                        showFeedback && index === pattern.correct 
                          ? 'bg-green-500 text-white border-green-500 hover:bg-green-600' 
                          : 'hover:bg-orange-50 hover:border-orange-300'
                      }`}
                    >
                      <div className={`flex items-center justify-center ${
                        pattern.type === 'size_progression' ? 'min-h-[120px] min-w-[120px]' : 'min-h-[60px] min-w-[60px]'
                      }`}>
                        {option && option.length > 0 ? (
                          option.map((element, elemIndex) => (
                            <div key={elemIndex} className="flex items-center justify-center">
                              {renderShape(element, pattern.type === 'size_progression' ? 85 : 52)}
                            </div>
                          ))
                        ) : (
                          <div className="w-12 h-12 bg-slate-100 border border-slate-300 rounded flex items-center justify-center text-slate-400">
                            ?
                          </div>
                        )}
                      </div>
                    </Button>
                  </motion.div>
                ))}
              </div>
              {pattern.type === 'size_progression' && (
                <div className="mt-4 text-center">
                  <p className="text-xs text-slate-500">
                    💡 提示：请仔细比较选项中图形的大小差异
                  </p>
                </div>
              )}
            </div>

            {/* 反馈区域 */}
            <AnimatePresence>
              {showFeedback && (
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  className={`text-center p-4 rounded-lg ${
                    feedbackCorrect 
                      ? 'bg-green-50 text-green-700 border border-green-200' 
                      : 'bg-red-50 text-red-700 border border-red-200'
                  }`}
                >
                  <div className="flex items-center justify-center gap-2 mb-2">
                    <span className="text-2xl">
                      {feedbackCorrect ? '✅' : '❌'}
                    </span>
                    <span className="font-semibold">
                      {feedbackCorrect ? '回答正确！' : '回答错误'}
                    </span>
                  </div>
                  {!feedbackCorrect && (
                    <div className="text-sm">
                      正确答案已用<span className="font-semibold text-green-600">绿色</span>标出
                    </div>
                  )}
                </motion.div>
              )}
            </AnimatePresence>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'results') {
    const totalPatterns = patterns.length;
    const correctAnswers = score;
    const accuracy = Math.round((correctAnswers / totalPatterns) * 100);

    const getRating = () => {
      if (accuracy >= 90) return { text: '模式大师', color: 'text-yellow-500' };
      if (accuracy >= 80) return { text: '优秀', color: 'text-green-500' };
      if (accuracy >= 70) return { text: '良好', color: 'text-blue-500' };
      if (accuracy >= 60) return { text: '一般', color: 'text-gray-500' };
      return { text: '需要提高', color: 'text-orange-500' };
    };

    const rating = getRating();

    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto space-y-6"
      >
        <Card>
          <CardHeader className="text-center">
            <CardTitle className="flex items-center justify-center gap-2">
              <CheckCircle className="w-6 h-6 text-orange-500" />
              测试完成！
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="text-center space-y-4">
              <div className="text-6xl font-bold text-primary">
                {accuracy}
              </div>
              <div className={`text-xl font-semibold ${rating.color}`}>
                {rating.text}
              </div>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center p-4 bg-green-50 dark:bg-green-950 rounded-lg">
                <div className="text-2xl font-bold text-green-600">{correctAnswers}</div>
                <div className="text-sm text-muted-foreground">正确</div>
              </div>
              <div className="text-center p-4 bg-red-50 dark:bg-red-950 rounded-lg">
                <div className="text-2xl font-bold text-red-600">{totalPatterns - correctAnswers}</div>
                <div className="text-sm text-muted-foreground">错误</div>
              </div>
              <div className="text-center p-4 bg-blue-50 dark:bg-blue-950 rounded-lg">
                <div className="text-2xl font-bold text-blue-600">{accuracy}%</div>
                <div className="text-sm text-muted-foreground">准确率</div>
              </div>
              <div className="text-center p-4 bg-purple-50 dark:bg-purple-950 rounded-lg">
                <div className="text-2xl font-bold text-purple-600">{totalPatterns}</div>
                <div className="text-sm text-muted-foreground">总题数</div>
              </div>
            </div>

            <div className="space-y-2">
              <h3 className="font-semibold">详细分析</h3>
              <div className="text-sm text-muted-foreground space-y-1">
                <p>• 完成了 {totalPatterns} 道模式识别测试题</p>
                <p>• 涵盖序列、矩阵、旋转、颜色、大小、形状等6个类型</p>
                <p>• 平均每题用时：{Math.round((Date.now() - startTime) / 1000 / totalPatterns)} 秒</p>
                {accuracy >= 85 && (
                  <p className="text-green-600">• 优秀：模式识别能力很强，逻辑思维敏捷</p>
                )}
                {accuracy < 70 && (
                  <p className="text-orange-600">• 建议：加强图形模式观察和逻辑推理训练</p>
                )}
              </div>
            </div>

            <div className="flex gap-4">
              <Button 
                onClick={resetTest} 
                variant="outline" 
                className="flex-1 border-2 border-slate-300 hover:border-slate-400 hover:bg-slate-50 text-slate-700 hover:text-slate-800 shadow-sm hover:shadow-md transition-all duration-300"
              >
                <RotateCcw className="w-4 h-4 mr-2" />
                重新测试
              </Button>
              <Button 
                onClick={handleComplete} 
                className="flex-1 bg-gradient-to-r from-orange-500 to-red-600 hover:from-orange-600 hover:to-red-700 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0"
              >
                <CheckCircle className="w-4 h-4 mr-2" />
                保存结果
              </Button>
            </div>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}